#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>

/*
void writer(int wfd)
{
  const char* str="Hello father,I am child process!";
   char buffer[128];
    int cnt=0;
    pid_t pid=getpid();
    while(1)
    {
        sleep(20);
        snprintf(buffer,sizeof(buffer),"%s,pid:%d,count:%d\n",str,pid,cnt);
        write(wfd,buffer,strlen(buffer));
        cnt++;
        //sleep(1);
    }
}
*/
//case 3:
/*void writer(int wfd)
{
    int cnt=0;
    while(1)
    {
        char c='M';
        write(wfd,&c,1);//每次写入1个字节
        cnt++;
        printf("cnt:%d\n",cnt);
        if(cnt==20)
        {
            break;
        }
    }
    close(wfd);
}
*/

/*void reader(int rfd) 
{
    char buffer[1024];
    while(1)
    {
        //case 2: sleep(60)
        sleep(1);
        ssize_t n=read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            printf("father get a message:%s,n:%ld\n",buffer,n);
        }
        else if(n==0)
        {
            printf("read pipe done,read file done!\n");
        }
        else
        {
            break;
        }
    }
}
*/

//case 4:
void writer(int wfd)
{
    int cnt=0;
    while(1)
    {
        sleep(1);
        char c='M';
        write(wfd,&c,1);//每次写入1个字节
        cnt++;
        printf("cnt:%d\n",cnt);
    }
}

void reader(int rfd) 
{
    sleep(5);
    close(rfd);
    printf("reader closed\n");
}

int main()
{
    int pipefd[2];
    int n=pipe(pipefd);
    if(n<0)
    {
        return 1;
    }
    printf("pipefd[0]:%d pipefd[1]:%d\n",pipefd[0],pipefd[1]);
    pid_t id=fork();
    if(id==0)
    {
        //child process:写端
        close(pipefd[0]);//子进程关闭读端
        writer(pipefd[1]);
    }
    //father process:读端
    close(pipefd[1]);//父进程关闭写端
    reader(pipefd[0]);
    int status=0;
    pid_t rid=waitpid(id,&status,0);
    if(rid>0)
    {
        printf("wait success! rid:%d,exit_code:%d,exit_signal:%d\n",rid,(status>>8)&0xFF,status&0x7F);
    }
    return 0;
}                        